package org.gvsig.titleblock.impl;

import java.util.ArrayList;

import org.gvsig.app.project.documents.layout.DefaultLayoutContext;
import org.gvsig.app.project.documents.layout.fframes.FFramePicture;
import org.gvsig.app.project.documents.layout.fframes.FFrameText;
import org.gvsig.app.project.documents.layout.fframes.IFFrame;
import org.gvsig.titleblock.IFFrameItem;
import org.gvsig.titleblock.IFFrames;
import org.gvsig.tools.ToolsLocator;
import org.gvsig.tools.dynobject.DynStruct;
import org.gvsig.tools.persistence.PersistenceManager;
import org.gvsig.tools.persistence.PersistentState;
import org.gvsig.tools.persistence.exception.PersistenceException;

/**
 * Represents a set of FFrames
 * @author Violeta
 *
 */
public class FFrames implements IFFrames{

	private IFFrame[] fframes;
	
	/**
	 * Constructor
	 */
	public FFrames() {
		// TODO Auto-generated constructor stub
	}
	
	public static void registerPersistent() {
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
        if (manager.getDefinition("fframesBox") == null) {
            DynStruct definition =
                manager.addDefinition(FFrames.class,
                    "fframesBox",
                    "FFrames persistence definition", null, null);
            definition.addDynFieldArray("fframes").setClassOfItems(IFFrame.class).setMandatory(true);
        }
    }
	
	/**
	 * Returns the array of FFrames
	 */
	public IFFrame[] getFframes() {
		return fframes;
	}

	/**
	 * Sets the array of FFrames
	 */
	public void setFframes(IFFrame[] fframes) {
		this.fframes = fframes;
	}

	/**
	 * Saves the state of the FFrames
	 */
	public void saveToState(PersistentState state) throws PersistenceException {
		state.set("fframes",this.fframes);
	}

	/**
	 * Load the FFrames from a state
	 */
	public void loadFromState(PersistentState state)
			throws PersistenceException {
		this.fframes = (IFFrame[]) ((ArrayList<IFFrame>)state.get("fframes")).toArray(new IFFrame[0]);
	}
	
	/**
	 * Returns an array of the picture items of the Frame.
	 */
	public IFFrameItem[] getPictureFrames() {
		ArrayList<FFrameItem> items=new ArrayList<FFrameItem>();
		items.add(new FFrameItem(null));
		for (int i = fframes.length-1; i >=0; i--) {
			if (fframes[i] instanceof FFramePicture){
				items.add(new FFrameItem(fframes[i]));
			}
		}
		return items.toArray(new FFrameItem[0]);
	}
	
	/**
	 * Returns an array of the text items of the Frame
	 */
	public IFFrameItem[] getTextFrames() {
		ArrayList<FFrameItem> items=new ArrayList<FFrameItem>();
		items.add(new FFrameItem(null));
		for (int i = fframes.length-1; i >=0; i--) {
			if (fframes[i] instanceof FFrameText){
				items.add(new FFrameItem(fframes[i]));
			}
		}
		return items.toArray(new FFrameItem[0]);
	}

}
